package ch09;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

public class BeanUtil {

	private static String setter;
	
	public static <T> T getBean(Map<String,Object> data,String clzName) throws Exception{
		Class clz = Class.forName(clzName);
		Object bean = clz.newInstance();
		
		data.entrySet().forEach(entry ->{
			String setter = String.format("set%s%s", 
					entry.getKey().substring(0,1).toUpperCase(),
					entry.getKey().substring(1));
			try{
				Method method = clz.getMethod(setter, entry.getValue().getClass());
				if(Modifier.isPublic(method.getModifiers())){
					method.invoke(bean, entry.getValue());
				}
			}catch (IllegalAccessException |IllegalArgumentException|
					NoSuchMethodException|SecurityException|InvocationTargetException e) {
				throw new RuntimeException(e);
			}
		});
		
		
		return (T) bean;
	}
}
